package com.excilys.formation.project.repository.impl;

import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.joda.time.Interval;
import org.springframework.stereotype.Repository;

import com.excilys.formation.project.entities.Transaction;
import com.excilys.formation.project.repository.TransactionDAO;

/**
 * 
 * @author excilys
 * 
 */
@Repository
public class TransactionDAOImpl implements TransactionDAO {
	/**
	 * EntityManager.
	 */
	@PersistenceContext
	EntityManager em;

	@Override
	public void save(Transaction transaction) {
		em.persist(em.merge(transaction));
	}

	@SuppressWarnings("unchecked")
	@Override
	public SortedSet<Transaction> getVirementsEmisByClientByTimeInterval(long clientId, Interval interval) {
		StringBuilder jpqlQSB = new StringBuilder("FROM Transaction t2 INNER JOIN FETCH t2.operations WHERE t2.id IN (");
		jpqlQSB.append("SELECT t.id FROM Transaction t INNER JOIN t.operations o INNER JOIN o.compte c ");
		jpqlQSB.append("WHERE c.client.id = :id ");
		jpqlQSB.append("AND o.type = 'VIREMENT' ");
		jpqlQSB.append("AND o.montant < 0 ");
		jpqlQSB.append("AND t.date BETWEEN :date_debut AND :date_fin ");
		jpqlQSB.append(")");
		Query q = em.createQuery(jpqlQSB.toString());
		q.setParameter("id", clientId);
		q.setParameter("date_debut", interval.getStart());
		q.setParameter("date_fin", interval.getEnd());

		return new TreeSet<Transaction>(q.getResultList());
	}

}
